import { Checkbox, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { maxTagPlaceholder } from '@src/components/antdRenders';
import { setArrayOnly } from '../../utils';
interface MyropTypes {
  on外层已经有的就不要再用antdProps里面的了?: any;
  optionList: any[];
  maxTagCount?: number;
  placeholder?: string;
  values?: any[];
  optionValue?: string;
  optionName?: string;
  onChange?: any;
  selectMoreOnChange?: any;
  onFocus?: any;
  onBlur?: any;
  onSearch?: any;
  antdProps?: any;
}
export const SelectMore = (props: MyropTypes) => {
  const antdProps = props.antdProps || {};
  const optionValue = props.optionValue || 'value';
  const optionName = props.optionName || 'name';
  const { Option } = Select;
  let selectValues = [];
  if (props.values?.length) {
    selectValues = props.values;
  }

  //当前下拉框选中的数据
  const [selectValue, setSelectValue] = useState<any>(selectValues);
  //手动控制下拉框展开还是合住
  const [openDropdown, setOpenDropdown] = useState<boolean>(false);
  //全选是否选中
  const [checkBoxAll, setCheckBoxAll] = useState<boolean>(false);
  //当前正在筛选的值
  const selectSearchValue = useRef<any>('');
  const productProgrammeList: any[] = props.optionList;
  const dropDownRender = (res: any) => {
    const { menu } = res;
    return (
      <div onMouseDown={(e) => e.preventDefault()}>
        {/* <div onMouseDown={(e) => e.preventDefault()}>{menu}</div> */}
        <div>{menu}</div>

        {productProgrammeList.length > 0 ? (
          <div style={{ paddingLeft: '10px' }}>
            <Checkbox
              checked={checkBoxAll}
              onChange={(e: any) => {
                // console.log('全选change', e.target.checked)
                setCheckBoxAll(e.target.checked);
                let allreadySelected = selectValue;
                if (e.target.checked) {
                  // console.log('数据要全选')
                  let finallySelectData = setArrayOnly([
                    ...allreadySelected,
                    ...currentShowOPtionidsF(optionName, optionValue),
                  ]);
                  setSelectValue(finallySelectData);
                } else {
                  // console.log("数据要quxiao全选", productProgrammeList);
                  let currentShowOPtionids = currentShowOPtionidsF(optionName, optionValue);
                  let allreadySelected = selectValue;
                  if (selectSearchValue.current) {
                    setSelectValue(
                      setArrayOnly(
                        allreadySelected.filter((item: any) => {
                          return !currentShowOPtionids.includes(item);
                        })
                      )
                    );
                  } else {
                    setSelectValue([]);
                  }
                }
                setOpenDropdown(false);
                selectSearchValue.current = '';
              }}
            >
              全选
            </Checkbox>
          </div>
        ) : null}
      </div>
    );
  };
  const onChange = (value: any, originValue: any) => {
    // console.log(value, originValue);
    setSelectValue(value);
  };
  useEffect(() => {
    console.log('-----------------------', selectValue, '-');
    sourceSelectAll();
    //如果是form表单会直接给props里面注册一个onChange事件 如果form表单里面的props里面就没有onchange方法
    props.onChange && props.onChange(selectValue);
    if (props.selectMoreOnChange) {
      let originValue: any[] = productProgrammeList.filter((item: any) => {
        return selectValue.some((item2: any) => item2 === item[optionValue]);
      });
      props.selectMoreOnChange(selectValue, originValue);
    }
  }, [selectValue]);
  const currentShowOPtionidsF = (nameKey: string = 'name', idKey: string = 'id') => {
    return productProgrammeList
      .filter((item2: any) => {
        return item2[nameKey].includes(selectSearchValue.current);
      })
      .map((item3: any) => item3[idKey]);
  };
  const sourceSelectAll = () => {
    const currentShowOPtionids = currentShowOPtionidsF(optionName, optionValue);
    if (selectValue.length === 0 || productProgrammeList.length === 0) {
      setCheckBoxAll(false);
      return;
    }
    if (
      currentShowOPtionids.every((item: any) => {
        return selectValue.includes(item);
      })
    ) {
      setCheckBoxAll(true);
    } else {
      setCheckBoxAll(false);
    }
  };
  return (
    <Select
      {...antdProps}
      value={selectValue}
      open={openDropdown}
      mode="multiple"
      maxTagCount={props.maxTagCount || 2}
      maxTagPlaceholder={(res: any) => {
        return maxTagPlaceholder(res);
      }}
      onChange={onChange}
      onFocus={(e: any) => {
        console.log('onFocus');
        setOpenDropdown(true);
        sourceSelectAll();
        props.onFocus && props.onFocus(e);
      }}
      onClick={() => {
        setOpenDropdown(true);
        sourceSelectAll();
      }}
      onBlur={(e: any) => {
        setTimeout(() => {
          setOpenDropdown(false);
          selectSearchValue.current = '';
          props.onBlur && props.onBlur(e);
        }, 50);
      }}
      showSearch
      allowClear
      placeholder={props.placeholder ? props.placeholder : '请选择'}
      optionFilterProp="children"
      onSearch={(value: any) => {
        console.log(value, selectValue);
        selectSearchValue.current = value;
        sourceSelectAll();
        props.onSearch && props.onSearch(value);
      }}
      dropdownRender={(menu: any) => {
        return dropDownRender({ menu });
      }}
    >
      {productProgrammeList.map((item: any) => {
        return (
          <Option key={item[optionValue]} value={item[optionValue]}>
            {item[optionName]}
          </Option>
        );
      })}
    </Select>
  );
};
